<template>
  <div class="form-single-fragment" style="position: relative;">
    <div class="form-single-info">
      <div class="form-single-btn clearfix">
        <el-button type="primary" @click="loadDesignateUser('agree')" v-if="btnbox">同意</el-button>
        <el-button @click="submitForm('refuse')" v-if="btnbox">拒绝</el-button>
        <el-button @click="resetForm()">返回</el-button>
      </div>
      <div class="form-single-btn clearfix" style="right: 120px;" v-if="detailData.verifyStatus==2">
        <img src="@/assets/img/adopt.png" />
      </div>
      <el-form :model="detailData" label-width="170px" size="mini" label-position="right">
        <el-row :gutter="20" class="form-single-info">
          <el-col :span="24">
            <el-col :span="12">
              <el-form-item label="任务名称：">{{detailData.taskName}}</el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="关联计划：">{{detailData.planName}}</el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="执行人：">{{detailData.executeUserName}}</el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="参与人：">{{detailData.userName}}
                <span v-for="(item, index) in detailData.participantsVoList" :key="index">{{item.userName}}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工作流程：">{{detailData.flowName}}</el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="设置截至时间：">{{detailData.endDate}}</el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="任务描述：">{{detailData.taskDesc}}</el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="工作流程：">{{detailData.flowName}}</el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="审核流程进度：">
                <ProcessViewer ref="ProcessViewers" :style="{height: (getMainContextHeight - 300) + 'px'}"
                  :xml="processXml"/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="上传附件">
                <el-upload class="upload-demo"
                  :action="action"
                  :on-change="handleSuccess"
                  :on-remove="handleRemove"
                  :before-upload="beforeAvatarUpload"
                  :accept="acceptStr"
                  multiple
                  :file-list="fileLists" v-if="btnbox">
                  <el-button size="small" type="primary">点击上传</el-button>
                  <div slot="tip" class="el-upload__tip">只能上传jpg/png/word/pdf/ppt文件，且不超过500MB</div>
                </el-upload>
                <div class="FileDoList" v-if="btnbox==false">
                  <div v-for="(item,index) in detailData.taskFileVoList" :key="index">
                    <span @click="filespreview(item)">{{item.fileName}}</span>
                    <strong @click="loadknowledgedownload(item)"><i class="el-icon-download"></i></strong>
                   </div>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="任务日志：">
                <el-timeline>
                  <el-timeline-item
                    v-for="(activity, index) in activities"
                    :key="index"
                    :timestamp="activity.createTime">
                    {{activity.userName}}：{{activity.content}}
                  </el-timeline-item>
                </el-timeline>
              </el-form-item>
            </el-col>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="annotation" v-if="examineFrombox">
      <examineFrom ref="examineFrom" @getexamineFrom="getexamineFrom" v-model="examineFrombox"></examineFrom>
    </div>
  </div>
</template>

<script>
import { Administration, fileUploadFileDo } from '@/api/projectAdministration.js';
import ProcessViewer from '@/views/workflow/components/ProcessViewer.vue';
import { mapGetters } from 'vuex';
import examineFrom from '@/components/selector/examineFrom.vue';
import Pdfpreview from '@/components/selector/Pdfpreview.vue';
import { FlowDesignatedController } from '@/api/flowController.js';
import TaskAssigneeSelect from '@/views/workflow/components/TaskAssigneeSelect.vue';
export default {
  name: 'ProjectsTasksExamine',
  components: { ProcessViewer, examineFrom },
  data () {
    return {
      isShowloading: false,
      examineFrombox: false,
      btnbox: true,
      activities: [],
      action: fileUploadFileDo,
      fileLists: [],
      acceptStr: '.doc,.docx,.xls,.xlsx,.jpg,.png,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      addtitle: '',
      activeName: '1',
      detailData: {},
      tableData: [],
      processXml: undefined,
      ruleForm: {
        fileIds: [],
        flowTaskCommentDto: {
          approvalType: '',
          comment: '',
          assignee: ''
        },
        id: '',
        taskId: ''
      }
    };
  },
  created () {
  },
  mounted () {
    if (this.$route.query.businessKey) {
      this.ruleForm.id = this.$route.query.businessKey
      this.ruleForm.taskId = this.$route.query.taskId
      this.loadDetailWidgetData()
    }
    if (this.$route.query.taskdetail) {
      this.btnbox = false
    }
  },
  computed: {
    ...mapGetters(['getMainContextHeight'])
  },
  methods: {
    /**
     * 项目任务详情
     */
    loadDetailWidgetData () {
      let params = {
        id: this.$route.query.businessKey
      };
      return new Promise((resolve, reject) => {
        Administration.taskview(this, params).then(res => {
          this.detailData = res.data
          this.processXml = res.data.bpmnXml
          setTimeout(() => {
            this.$nextTick(() => {
              this.$refs.ProcessViewers.processReZoom()
            });
          }, 500)
          this.loadTasklogWidgetData()
          this.ruleForm.fileIds = []
          let file = res.data.taskFileVoList
          if (file && file.length !== 0) {
            file.forEach((item) => {
              this.ruleForm.fileIds.push(item.fileId)
            })
            this.fileLists = file.map(items => {
              return {
                name: items.fileName,
                response: {
                  data: items
                }
              }
            })
          }
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
     * 任务日志
     */
    loadTasklogWidgetData () {
      let params = {
        taskId: this.detailData.id,
        logType: 2
      };
      return new Promise((resolve, reject) => {
        Administration.tasklog(this, params).then(res => {
          this.activities = res.data
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
     * 上传文件-成功
     */
    handleSuccess (file, fileList) {
      this.fileLists = fileList
    },
    /**
     * 上传文件-删除
     */
    handleRemove (file, fileList) {
      this.fileLists = fileList
    },
    /**
     * 上传图片限制条件
     */
    beforeAvatarUpload (file, fileList) {
      // const isJPG = file.type === 'image/jpeg'
      // const isLt200K = file.size / 1024 < 200
      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!')
      //   return false
      // }
      // if (!isLt200K) {
      //   this.$message.error('上传头像图片大小不能超过 200KB!')
      //   return false
      // }
      // return isJPG && isLt200K
    },
    /**
     * pdf预览
     */
    filespreview (data) {
      let params = {
        files: data.pdfPath
      };
      this.$dialog.show(data.fileName, Pdfpreview, {
        area: ['100%', '100%']
      }, params).then(res => {
        this.loadknowledgedetail()
      }).catch(e => {
      });
    },
    /**
     * 文件下载
     */
    loadknowledgedownload (data) {
      if (data.fileType === 'jpg' || data.fileType === 'png') {
        window.open(data.pdfPath)
      } else {
        window.open(data.filePath)
      }
    },
    // 选择审批人
    loadDesignateUser (value) {
      this.ruleForm.flowTaskCommentDto.assignee = '';
      this.ruleForm.flowTaskCommentDto.assigneeName = '';
      let params = {
        taskId: this.$route.query.taskId,
        processInstanceId: this.$route.query.processInstanceId
      }
      FlowDesignatedController.getStartProcessDesignateUser(this, params).then(res => {
        if (res.data && (this.ruleForm.flowTaskCommentDto.assignee === '' || this.ruleForm.flowTaskCommentDto.assignee === undefined)) {
          this.$dialog.show('选择审批人', TaskAssigneeSelect, {
            area: ['1000px', '600px']
          }, {
            multiple: false,
            userTable: res.data
          }).then(res => {
            let assignee = null;
            let assigneeName = null;
            if (Array.isArray(res)) {
              assignee = res.map(item => item.loginName).join(',');
              assigneeName = res.map(item => item.showName).join(',');
            } else {
              assignee = (res || {}).loginName;
              assigneeName = (res || {}).showName;
            }
            this.ruleForm.flowTaskCommentDto.assignee = assignee;
            this.ruleForm.flowTaskCommentDto.assigneeName = assigneeName;
            this.$forceUpdate()
            this.submitForm(value)
          }).catch(e => {});
        } else {
          this.submitForm(value)
        }
      })
    },
    /**
     * 审批
     */
    submitForm (data) {
      this.ruleForm.flowTaskCommentDto.approvalType = data
      this.examineFrombox = true
      this.$nextTick(() => {
        this.$refs.examineFrom.info(this.ruleForm.flowTaskCommentDto.assigneeName)
      })
    },
    getexamineFrom (data) {
      this.isShowloading = true;
      this.ruleForm.flowTaskCommentDto.comment = data.comment
      if (this.fileLists.length !== 0) {
        let filesnew = []
        this.fileLists.forEach((item) => {
          filesnew.push(item.response.data.fileId)
        })
        this.ruleForm.fileIds = filesnew
      }
      let params = this.ruleForm;
      return new Promise((resolve, reject) => {
        Administration.submitUserTask(this, params).then(res => {
          this.$message({
            showClose: true,
            message: '操作成功！',
            type: 'success'
          });
          this.resetForm()
        }).catch(e => {
          reject(e);
        });
      });
    },
    resetForm () {
      this.$router.go(-1)
    }
  }
}
</script>

<style lang="scss" scoped>
h3{border-bottom: 1px solid #E9E9EB;padding: 0 0 10px;}
.table_container{margin: 10px 0;}
.form-single-info{width: 90%;margin: 0 auto;}
/deep/.el-tabs__nav{left: inherit;}
/deep/.el-tabs__item{text-align: center;}
/deep/.el-tabs__nav-wrap::after{display: none;}
/deep/.el-tabs__item.is-active{color: #051D69;font-weight: bold;}
/deep/.el-tabs__active-bar{background-color: #051D69;}
.form-single-btn{position: absolute;right: 20px;top: 20px;z-index: 20;}
</style>
